package yto.freemarker.springbootstudy.controller;

import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import yto.freemarker.springbootstudy.entity.App;
import yto.freemarker.springbootstudy.entity.User;
import yto.freemarker.springbootstudy.mapper.AppMapper;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author dongxing
 * @create 2018-02-23 16:40
 **/
@RestController
@RequestMapping("/d")
@AllArgsConstructor(onConstructor = @_(@Autowired))
public class UserController {

    private final AppMapper appMapper;

    @GetMapping("/h/{id}")
    public App getHello3(@PathVariable Integer id, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        App app = appMapper.selectByPrimaryKey(id);
        return app;
    }

    @GetMapping("/h")
    public List<App> getHello(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return appMapper.selectAll();
    }


//    @RequestMapping("/")
//    public String home(Model model) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        Object principal = authentication.getPrincipal();
//        return "index";
//    }
//    @RequestMapping("/login")
//    public App login(Model model,HttpServletResponse response) {
//        response.setContentType("text/html;charset=utf-8");
//        App app = appMapper.selectByPrimaryKey(1);
//        return app;
//    }

    /**
     * 效验规则
     *
     * @param user
     * @param bindingResult
     * @return
     */
    @PostMapping("/girls")
    public User addGirl(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        return user;
    }


    @GetMapping("/alls")
    public List<App> getAll() {
        List<App> all = appMapper.findAll();
        return all;
    }

    @GetMapping("/{id}")
    public App getById(@PathVariable Integer id) {
        return appMapper.findById(id);
    }

    @PostMapping("/user")
    public void addUser(App app) {
        appMapper.addApp(app);

    }

    @PostMapping("/user/1")
    public Integer updateA(App app) {
        int i = appMapper.updateById(app);
        return i;
    }


}
